//
//  refresh.swift
//  自定义刷新
//
//  Created by 张城 on 16/7/25.
//  Copyright © 2016年 张城. All rights reserved.
//

import UIKit


enum RefreshStateType: Int {
    case Normal = 0
    case Pull = 1
    case Refreshing = 2
}

class refresh: UIControl {
    
    private lazy var stateLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(16)
        label.text = "正常"
        label.textColor = UIColor.redColor()
        return label
    }()
    
    private lazy var jiantouImg: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var indicator: UIActivityIndicatorView = {
        let indi = UIActivityIndicatorView(activityIndicatorStyle: .White)
        indi.color = UIColor.redColor()
        return indi
    }()
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, -50, UIScreen.mainScreen().bounds.width, 50))
        backgroundColor = UIColor.brownColor()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(stateLabel)
        addSubview(jiantouImg)
        addSubview(indicator)
        
        stateLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: stateLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: stateLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        jiantouImg.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: jiantouImg, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: jiantouImg, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicator, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
    }
    
    var scrollView: UIScrollView?
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        self.scrollView = scrollView
        self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        getRefreshStates((self.scrollView?.contentOffset.y) ?? 0)
    }
    
    var states: RefreshStateType = .Normal{
        didSet{
            switch states {
            case .Normal:
                self.stateLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: {
                    self.jiantouImg.transform = CGAffineTransformIdentity
                })
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: {
                        self.scrollView?.contentInset.top -= 50
                        }, completion: { (_) in
                            self.jiantouImg.hidden = false
                            self.indicator.stopAnimating()
                    })
                }
            case .Pull:
                self.stateLabel.text = "下拉"
                UIView.animateWithDuration(0.25, animations: {
                    self.jiantouImg.transform = CGAffineTransformMakeRotation(CGFloat(-3*M_PI))
                })
            case .Refreshing:
                self.stateLabel.text = "刷新中"
                self.jiantouImg.hidden = true
                self.indicator.startAnimating()
                UIView.animateWithDuration(0.25, animations: {
                    self.scrollView?.contentInset.top += 50
                    }, completion: { (_) in
                        self.sendActionsForControlEvents(.ValueChanged)
                })
            }
        }
    }
    
    func endRefresh() {
        states = .Normal
    }
    
    func getRefreshStates(contentOffsety: CGFloat) {
        let contentTop = self.scrollView?.contentInset.top ?? 0
        if (self.scrollView!.dragging) {
            if contentOffsety <= -contentTop-50 && states == .Normal{
                states = .Pull
            }else if contentOffsety > -contentTop-50 && states == .Pull{
                states = .Normal
            }
        }else{
            if states == .Pull {
                states = .Refreshing
            }
        }
    }
    
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: nil)
    }
}
